<template>
  <div class="dynamic-backgrounds">
    <el-card class="header-card">
      <div class="page-header">
        <div class="header-left">
          <h2>🎨 动态背景管理</h2>
          <p class="subtitle">精美动态背景，让您的系统更具个性</p>
        </div>
        <div class="header-right">
          <el-button type="primary" @click="showCurrentBackground">
            <el-icon><View /></el-icon>
            当前背景
          </el-button>
          <el-button @click="showSettings">
            <el-icon><Setting /></el-icon>
            设置
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 筛选和搜索 -->
    <el-card class="filter-card">
      <div class="filter-bar">
        <div class="filter-left">
          <el-radio-group v-model="activeCategory" @change="handleCategoryChange">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="favorites">我的收藏</el-radio-button>
            <el-radio-button label="particle">粒子效果</el-radio-button>
            <el-radio-button label="gradient">渐变动画</el-radio-button>
            <el-radio-button label="wave">波浪流动</el-radio-button>
            <el-radio-button label="star">星空宇宙</el-radio-button>
            <el-radio-button label="geometry">几何图形</el-radio-button>
            <el-radio-button label="abstract">抽象艺术</el-radio-button>
            <el-radio-button label="matrix">矩阵代码</el-radio-button>
            <el-radio-button label="bubble">气泡效果</el-radio-button>
            <el-radio-button label="snow">雪花飘落</el-radio-button>
          </el-radio-group>
        </div>
        <div class="filter-right">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索背景..."
            clearable
            style="width: 250px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>
    </el-card>

    <!-- 背景列表 -->
    <div class="backgrounds-grid">
      <el-card
        v-for="bg in filteredBackgrounds"
        :key="bg.id"
        class="background-card"
        :class="{ active: currentBackground?.id === bg.id }"
        shadow="hover"
      >
        <div class="background-preview" @click="previewBackground(bg)">
          <component 
            :is="getBackgroundComponent(bg.type)" 
            :config="bg.config"
            :key="`card-${bg.id}`"
          />
          <div class="preview-overlay">
            <el-button circle @click.stop="toggleFavorite(bg)">
              <el-icon :class="{ favorited: bg.isFavorite }">
                <component :is="bg.isFavorite ? StarFilled : Star" />
              </el-icon>
            </el-button>
          </div>
          <div v-if="currentBackground?.id === bg.id" class="active-badge">
            <el-tag type="success" effect="dark">使用中</el-tag>
          </div>
        </div>
        <div class="background-info">
          <div class="info-header">
            <h4>{{ bg.name }}</h4>
            <el-tag :type="getCategoryType(bg.category)" size="small">
              {{ getCategoryName(bg.category) }}
            </el-tag>
          </div>
          <p class="description">{{ bg.description }}</p>
          <div class="actions">
            <el-button size="small" type="primary" @click="applyBackground(bg)">
              <el-icon><Check /></el-icon>
              应用
            </el-button>
            <el-button size="small" @click="previewBackground(bg)">
              <el-icon><View /></el-icon>
              预览
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

  </div>
</template>

<script setup>
import { ref, computed, markRaw, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Search, View, Setting, Star, StarFilled, Check
} from '@element-plus/icons-vue'

// 动态背景组件
import ParticleBackground from './backgrounds/ParticleBackground.vue'
import GradientBackground from './backgrounds/GradientBackground.vue'
import WaveBackground from './backgrounds/WaveBackground.vue'
import StarBackground from './backgrounds/StarBackground.vue'
import GeometryBackground from './backgrounds/GeometryBackground.vue'
import AbstractBackground from './backgrounds/AbstractBackground.vue'
import MatrixBackground from './backgrounds/MatrixBackground.vue'
import BubbleBackground from './backgrounds/BubbleBackground.vue'
import SnowBackground from './backgrounds/SnowBackground.vue'
import FireworksBackground from './backgrounds/FireworksBackground.vue'
import ScanBackground from './backgrounds/ScanBackground.vue'
import NeonBackground from './backgrounds/NeonBackground.vue'

const activeCategory = ref('all')
const searchKeyword = ref('')
const currentBackground = ref(null)

// 背景数据
const backgrounds = ref([
  // 粒子效果
  {
    id: 1,
    name: '浮动粒子',
    description: '轻盈的粒子在屏幕上缓缓飘动，营造梦幻氛围',
    category: 'particle',
    type: 'particle',
    isFavorite: false,
    config: {
      count: 50,
      speed: 'slow',
      color: '#667eea',
      size: 'medium'
    }
  },
  {
    id: 2,
    name: '星光闪烁',
    description: '闪烁的粒子如星光般点缀屏幕',
    category: 'particle',
    type: 'particle',
    isFavorite: false,
    config: {
      count: 80,
      speed: 'medium',
      color: '#ffd700',
      size: 'small',
      twinkle: true
    }
  },
  {
    id: 3,
    name: '彩色泡泡',
    description: '多彩的泡泡效果，充满活力',
    category: 'particle',
    type: 'particle',
    isFavorite: false,
    config: {
      count: 30,
      speed: 'medium',
      color: 'rainbow',
      size: 'large',
      shape: 'bubble'
    }
  },
  // 渐变动画
  {
    id: 4,
    name: '紫色梦幻',
    description: '紫色系渐变，优雅神秘',
    category: 'gradient',
    type: 'gradient',
    isFavorite: true,
    config: {
      colors: ['#667eea', '#764ba2', '#f093fb'],
      direction: 'diagonal',
      speed: 15
    }
  },
  {
    id: 5,
    name: '日落余晖',
    description: '温暖的橙红渐变，如日落般美丽',
    category: 'gradient',
    type: 'gradient',
    isFavorite: false,
    config: {
      colors: ['#fa709a', '#fee140'],
      direction: 'horizontal',
      speed: 20
    }
  },
  {
    id: 6,
    name: '深海蓝调',
    description: '深邃的蓝色渐变，宁静优雅',
    category: 'gradient',
    type: 'gradient',
    isFavorite: false,
    config: {
      colors: ['#0f2027', '#203a43', '#2c5364'],
      direction: 'vertical',
      speed: 25
    }
  },
  // 波浪流动
  {
    id: 7,
    name: '温柔波浪',
    description: '柔和的波浪在屏幕底部流动',
    category: 'wave',
    type: 'wave',
    isFavorite: true,
    config: {
      layers: 3,
      speed: 'slow',
      color: '#0078d4',
      amplitude: 'medium'
    }
  },
  {
    id: 8,
    name: '海洋波涛',
    description: '层叠的蓝色波浪，如海洋般壮阔',
    category: 'wave',
    type: 'wave',
    isFavorite: false,
    config: {
      layers: 4,
      speed: 'medium',
      color: '#1e90ff',
      amplitude: 'large'
    }
  },
  {
    id: 9,
    name: '彩虹流',
    description: '多彩的波浪流动，绚丽多姿',
    category: 'wave',
    type: 'wave',
    isFavorite: false,
    config: {
      layers: 3,
      speed: 'fast',
      color: 'gradient',
      amplitude: 'small'
    }
  },
  // 星空宇宙
  {
    id: 10,
    name: '浩瀚星空',
    description: '繁星点点，如夜空般深邃',
    category: 'star',
    type: 'star',
    isFavorite: true,
    config: {
      density: 'high',
      speed: 'slow',
      shooting: true
    }
  },
  {
    id: 11,
    name: '银河系',
    description: '流动的银河，神秘璀璨',
    category: 'star',
    type: 'star',
    isFavorite: false,
    config: {
      density: 'medium',
      speed: 'medium',
      nebula: true
    }
  },
  {
    id: 12,
    name: '星际穿越',
    description: '快速移动的星点，穿越星际',
    category: 'star',
    type: 'star',
    isFavorite: false,
    config: {
      density: 'medium',
      speed: 'fast',
      trail: true
    }
  },
  // 几何图形
  {
    id: 13,
    name: '几何矩阵',
    description: '规律的几何图形组成动态矩阵',
    category: 'geometry',
    type: 'geometry',
    isFavorite: false,
    config: {
      shape: 'squares',
      color: '#667eea',
      animation: 'pulse'
    }
  },
  {
    id: 14,
    name: '三角迷阵',
    description: '三角形组成的动态迷阵',
    category: 'geometry',
    type: 'geometry',
    isFavorite: false,
    config: {
      shape: 'triangles',
      color: '#00d4ff',
      animation: 'rotate'
    }
  },
  {
    id: 15,
    name: '圆形舞动',
    description: '圆形元素的优雅舞蹈',
    category: 'geometry',
    type: 'geometry',
    isFavorite: false,
    config: {
      shape: 'circles',
      color: '#ff6b6b',
      animation: 'float'
    }
  },
  // 抽象艺术
  {
    id: 16,
    name: '流体艺术',
    description: '如流动的颜料般的抽象艺术',
    category: 'abstract',
    type: 'abstract',
    isFavorite: false,
    config: {
      style: 'fluid',
      colors: ['#667eea', '#764ba2', '#f093fb']
    }
  },
  {
    id: 17,
    name: '线条世界',
    description: '交织的线条构成抽象世界',
    category: 'abstract',
    type: 'abstract',
    isFavorite: false,
    config: {
      style: 'lines',
      colors: ['#00d4ff', '#0078d4']
    }
  },
  {
    id: 18,
    name: '光影交错',
    description: '光影的交错营造奇妙效果',
    category: 'abstract',
    type: 'abstract',
    isFavorite: false,
    config: {
      style: 'light',
      colors: ['#ffd60a', '#ff9500']
    }
  },
  // 矩阵代码
  {
    id: 19,
    name: '黑客帝国',
    description: '经典的绿色矩阵代码雨',
    category: 'matrix',
    type: 'matrix',
    isFavorite: true,
    config: {
      color: '#00ff00',
      speed: 'medium',
      density: 'high'
    }
  },
  {
    id: 20,
    name: '蓝色矩阵',
    description: '蓝色主题的数字代码流',
    category: 'matrix',
    type: 'matrix',
    isFavorite: false,
    config: {
      color: '#00d4ff',
      speed: 'fast',
      density: 'medium'
    }
  },
  {
    id: 21,
    name: '彩虹代码',
    description: '多彩的代码矩阵，炫丽夺目',
    category: 'matrix',
    type: 'matrix',
    isFavorite: false,
    config: {
      color: 'rainbow',
      speed: 'slow',
      density: 'low'
    }
  },
  // 气泡效果
  {
    id: 22,
    name: '梦幻气泡',
    description: '彩色气泡缓缓上升，梦幻童话',
    category: 'bubble',
    type: 'bubble',
    isFavorite: true,
    config: {
      count: 20,
      speed: 'slow',
      color: 'rainbow',
      size: 'large'
    }
  },
  {
    id: 23,
    name: '海底泡泡',
    description: '蓝色气泡从底部升起',
    category: 'bubble',
    type: 'bubble',
    isFavorite: false,
    config: {
      count: 30,
      speed: 'medium',
      color: '#0078d4',
      size: 'medium'
    }
  },
  {
    id: 24,
    name: '香槟庆典',
    description: '金色气泡快速上升，庆典氛围',
    category: 'bubble',
    type: 'bubble',
    isFavorite: false,
    config: {
      count: 40,
      speed: 'fast',
      color: '#ffd700',
      size: 'small'
    }
  },
  // 雪花飘落
  {
    id: 25,
    name: '浪漫雪夜',
    description: '雪花纷纷扬扬，浪漫唯美',
    category: 'snow',
    type: 'snow',
    isFavorite: true,
    config: {
      count: 100,
      speed: 'slow',
      wind: 'light'
    }
  },
  {
    id: 26,
    name: '暴风雪',
    description: '密集的雪花快速飘落',
    category: 'snow',
    type: 'snow',
    isFavorite: false,
    config: {
      count: 200,
      speed: 'fast',
      wind: 'strong'
    }
  },
  {
    id: 27,
    name: '樱花飞舞',
    description: '粉色花瓣随风飘舞',
    category: 'snow',
    type: 'snow',
    isFavorite: false,
    config: {
      count: 80,
      speed: 'medium',
      wind: 'medium',
      color: '#ffb6c1'
    }
  },
  // 烟花效果
  {
    id: 28,
    name: '璀璨烟花',
    description: '绚丽的烟花在夜空绽放',
    category: 'particle',
    type: 'fireworks',
    isFavorite: true,
    config: {
      frequency: 'medium',
      colors: 'rainbow'
    }
  },
  {
    id: 29,
    name: '节日庆典',
    description: '密集的烟花庆祝氛围',
    category: 'particle',
    type: 'fireworks',
    isFavorite: false,
    config: {
      frequency: 'high',
      colors: ['#ff0000', '#00ff00', '#0000ff', '#ffff00']
    }
  },
  // 扫描效果
  {
    id: 30,
    name: '科技扫描',
    description: '蓝色扫描线往复移动',
    category: 'abstract',
    type: 'scan',
    isFavorite: false,
    config: {
      color: '#00d4ff',
      speed: 'medium',
      style: 'horizontal'
    }
  },
  {
    id: 31,
    name: '雷达扫描',
    description: '旋转的雷达扫描效果',
    category: 'abstract',
    type: 'scan',
    isFavorite: false,
    config: {
      color: '#00ff00',
      speed: 'slow',
      style: 'radar'
    }
  },
  // 霓虹效果
  {
    id: 32,
    name: '霓虹都市',
    description: '霓虹灯管的流光溢彩',
    category: 'abstract',
    type: 'neon',
    isFavorite: false,
    config: {
      style: 'lines',
      colors: ['#ff006e', '#fb5607', '#ffbe0b', '#8338ec']
    }
  },
  {
    id: 33,
    name: '霓虹网格',
    description: '网格状的霓虹光效',
    category: 'abstract',
    type: 'neon',
    isFavorite: false,
    config: {
      style: 'grid',
      colors: ['#00d4ff', '#0078d4']
    }
  }
])

// 筛选后的背景
const filteredBackgrounds = computed(() => {
  let result = backgrounds.value

  // 分类筛选
  if (activeCategory.value === 'favorites') {
    result = result.filter(bg => bg.isFavorite)
  } else if (activeCategory.value !== 'all') {
    result = result.filter(bg => bg.category === activeCategory.value)
  }

  // 搜索筛选
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(bg =>
      bg.name.toLowerCase().includes(keyword) ||
      bg.description.toLowerCase().includes(keyword)
    )
  }

  return result
})

// 获取背景组件
const getBackgroundComponent = (type) => {
  const components = {
    particle: markRaw(ParticleBackground),
    gradient: markRaw(GradientBackground),
    wave: markRaw(WaveBackground),
    star: markRaw(StarBackground),
    geometry: markRaw(GeometryBackground),
    abstract: markRaw(AbstractBackground),
    matrix: markRaw(MatrixBackground),
    bubble: markRaw(BubbleBackground),
    snow: markRaw(SnowBackground),
    fireworks: markRaw(FireworksBackground),
    scan: markRaw(ScanBackground),
    neon: markRaw(NeonBackground)
  }
  return components[type] || components.gradient
}

// 获取分类名称
const getCategoryName = (category) => {
  const names = {
    particle: '粒子',
    gradient: '渐变',
    wave: '波浪',
    star: '星空',
    geometry: '几何',
    abstract: '抽象',
    matrix: '矩阵',
    bubble: '气泡',
    snow: '雪花'
  }
  return names[category] || category
}

// 获取分类类型
const getCategoryType = (category) => {
  const types = {
    particle: 'primary',
    gradient: 'success',
    wave: 'info',
    star: 'warning',
    geometry: 'danger',
    abstract: '',
    matrix: 'success',
    bubble: 'primary',
    snow: 'info'
  }
  return types[category] || ''
}

// 切换收藏
const toggleFavorite = (bg) => {
  bg.isFavorite = !bg.isFavorite
  ElMessage.success(bg.isFavorite ? '已添加到收藏' : '已取消收藏')
}

// 预览背景（打开新窗口）
const previewBackground = (bg) => {
  // 将背景配置编码到URL
  const configStr = encodeURIComponent(JSON.stringify(bg))
  const previewUrl = `/system/background-preview?config=${configStr}`
  
  // 打开新窗口
  const width = Math.min(1200, window.screen.width * 0.8)
  const height = Math.min(800, window.screen.height * 0.8)
  const left = (window.screen.width - width) / 2
  const top = (window.screen.height - height) / 2
  
  window.open(
    previewUrl,
    `背景预览 - ${bg.name}`,
    `width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=no,status=no,toolbar=no,menubar=no,location=no`
  )
}

// 应用背景
const applyBackground = (bg) => {
  currentBackground.value = bg
  // 这里可以保存到localStorage或发送到后端
  localStorage.setItem('currentBackground', JSON.stringify(bg))
  ElMessage.success(`已应用背景：${bg.name}`)
}

// 显示当前背景
const showCurrentBackground = () => {
  if (currentBackground.value) {
    previewBackground(currentBackground.value)
  } else {
    ElMessage.info('当前未设置背景')
  }
}

// 监听来自预览窗口的消息
const handleMessage = (event) => {
  if (event.data.type === 'applyBackground') {
    applyBackground(event.data.data)
  }
}

onMounted(() => {
  loadCurrentBackground()
  window.addEventListener('message', handleMessage)
})

onUnmounted(() => {
  window.removeEventListener('message', handleMessage)
})

// 显示设置
const showSettings = () => {
  ElMessage.info('设置功能开发中...')
}

// 分类切换
const handleCategoryChange = () => {
  // 可以在这里添加额外逻辑
}

// 初始化：从localStorage读取当前背景
const loadCurrentBackground = () => {
  const saved = localStorage.getItem('currentBackground')
  if (saved) {
    try {
      currentBackground.value = JSON.parse(saved)
    } catch (e) {
      console.error('加载背景失败:', e)
    }
  }
}
</script>

<style scoped>
.dynamic-backgrounds {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #303133;
}

.subtitle {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.header-right {
  display: flex;
  gap: 12px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.filter-left {
  flex: 1;
}

/* 背景网格 */
.backgrounds-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
}

.background-card {
  transition: all 0.3s ease;
}

.background-card.active {
  border-color: #67c23a;
  box-shadow: 0 2px 12px rgba(103, 194, 58, 0.3);
}

.background-preview {
  position: relative;
  width: 100%;
  height: 200px;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  margin-bottom: 16px;
  background: #000;
}

.background-preview > * {
  position: absolute !important;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.preview-overlay {
  position: absolute !important;
  top: 8px;
  right: 8px;
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: 10;
}

.background-card:hover .preview-overlay {
  opacity: 1;
}

.preview-overlay .el-button {
  background: rgba(255, 255, 255, 0.9);
}

.favorited {
  color: #f56c6c;
}

.active-badge {
  position: absolute !important;
  top: 8px;
  left: 8px;
  z-index: 10;
}

.background-info {
  padding: 0 4px;
}

.info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.info-header h4 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.description {
  margin: 0 0 12px 0;
  font-size: 13px;
  color: #909399;
  line-height: 1.5;
}

.actions {
  display: flex;
  gap: 8px;
}

/* 响应式 */
@media (max-width: 768px) {
  .backgrounds-grid {
    grid-template-columns: 1fr;
  }
  
  .filter-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-left,
  .filter-right {
    width: 100%;
  }
  
  :deep(.el-radio-group) {
    display: flex;
    flex-wrap: wrap;
  }
}
</style>

